const { DataTypes, Op } = require('sequelize');
const sequelize = require('@shared/utils/database');
const crypto = require('crypto');

const User = sequelize.define('User', {
  id: {
    type: DataTypes.BIGINT,
    primaryKey: true,
    autoIncrement: true,
    comment: '用户ID'
  },
  username: {
    type: DataTypes.STRING(32),
    allowNull: true,
    comment: '用户名'
  },
  nickname: {
    type: DataTypes.STRING(32),
    allowNull: true,
    comment: '昵称'
  },
  password: {
    type: DataTypes.STRING(32),
    allowNull: true,
    comment: '密码',
    set(value) {
      if (value) {
        // 使用MD5加密
        const md5 = crypto.createHash('md5');
        const hash = md5.update(value).digest('hex');
        this.setDataValue('password', hash);
      }
    }
  },
  name: {
    type: DataTypes.STRING(32),
    allowNull: true,
    comment: '姓名'
  },
  phone: {
    type: DataTypes.STRING(11),
    allowNull: true,
    comment: '手机号'
  },
  // 微信相关字段
  openid: {
    type: DataTypes.STRING(64),
    allowNull: true,
    comment: '微信openid'
  },
  unionid: {
    type: DataTypes.STRING(64),
    allowNull: true,
    comment: '微信unionid'
  },
  avatar: {
    type: DataTypes.STRING(256),
    allowNull: true,
    comment: '头像URL'
  },
  gender: {
    type: DataTypes.TINYINT,
    allowNull: true,
    comment: '性别：0-未知 1-男 2-女'
  },
  country: {
    type: DataTypes.STRING(32),
    allowNull: true,
    comment: '国家'
  },
  province: {
    type: DataTypes.STRING(32),
    allowNull: true,
    comment: '省份'
  },
  city: {
    type: DataTypes.STRING(32),
    allowNull: true,
    comment: '城市'
  },
  status: {
    type: DataTypes.TINYINT,
    allowNull: false,
    defaultValue: 1,
    comment: '状态：0-禁用 1-正常'
  },
  last_login_time: {
    type: DataTypes.DATE,
    allowNull: true,
    comment: '最后登录时间'
  }
}, {
  tableName: 'user',
  timestamps: true,
  createdAt: 'create_time',
  updatedAt: 'update_time'
});

// 密码验证方法
User.prototype.comparePassword = function(password) {
  if (!this.password) return false;
  const md5 = crypto.createHash('md5');
  const hash = md5.update(password).digest('hex');
  return this.password === hash;
};

module.exports = User; 